package com.fuze.aspect;

import com.fuze.common.Advice;
import com.fuze.common.CustomException;
import com.fuze.common.constant.Constant;
import com.fuze.domain.model.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sepc_
 * @date 4/20/2021 09:14
 */
@RequiredArgsConstructor
@Slf4j
@Component
@Aspect
public class AuthUserAspect {

    final RedisTemplate<String, Object> redisTemplate;

    final HttpServletRequest request;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.fuze.aspect.anno.AuthUser)")
    public void authPointCut() {
    }

    /**
     * 处理请求之前执行：校验token的角色
     */
    @Before(value = "authPointCut()")
    public void doBefore(JoinPoint point) {
        String token = request.getHeader(Constant.AUTH_TOKEN);
        Object o = redisTemplate.opsForValue().get(token);
        if (o == null) {
            throw new CustomException(Advice.TOKEN_EXPIRED);
        }
        //如果是管理员直接放行不处理，
        if (o instanceof User) {
            //是用户判断是否绑定了
            User user = (User) o;
            if (user.getBindType().equals(Constant.UNBOUND)) {
                throw new CustomException(Advice.UNBOUND_UNAUTHORIZED);
            }
        }
    }

}
